package com.pactera.miyuangroup.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.pactera.miyuangroup.common.Constants;
import com.pactera.miyuangroup.common.RedisOperation;
import com.pactera.miyuangroup.db.entity.GoodsInfo;
import com.pactera.miyuangroup.db.mapper.GoodsInfoMapper;
import com.pactera.miyuangroup.service.GoodsInfoService;
import com.pactera.miyuangroup.service.MiyuanDataService;
import com.pactera.miyuangroup.vo.request.web.GoodsInfoReques;
import com.pactera.miyuangroup.vo.response.miyuan.MiYuanModel;
import com.pactera.miyuangroup.vo.response.miyuan.MiYuanPage;
import com.pactera.miyuangroup.vo.response.web.GoodsInfoRes;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 商品信息 服务实现类
 * </p>
 *
 * @author WangWu
 * @since 2018-04-13
 */
@Service
@Slf4j
public class GoodsInfoServiceImp extends ServiceImpl<GoodsInfoMapper, GoodsInfo> implements GoodsInfoService {
    @Autowired
    private MiyuanDataService miyuanDataService;

    @Autowired
    private RedisOperation redis;


    @Override
    public Page<GoodsInfoRes> getGoodsInfoList(GoodsInfoReques goodsInfoReques) {
        //验证数据
        EntityWrapper wrapper = new EntityWrapper();
        if (StringUtils.isNotBlank(goodsInfoReques.getNumber())) {
            wrapper.eq("`goods`.`number`", goodsInfoReques.getNumber());
        }

        if (StringUtils.isNotBlank(goodsInfoReques.getClassification())) {
            wrapper.eq("`goods`.`classification`", goodsInfoReques.getClassification());
        }

        if (StringUtils.isNotBlank(goodsInfoReques.getName())) {
            wrapper.eq("`goods`.`name`", goodsInfoReques.getName());
        }

        if (StringUtils.isNotBlank(goodsInfoReques.getSpecifications())) {
            wrapper.eq("`goods`.`specifications`", goodsInfoReques.getSpecifications());
        }

        //查询数据
        Page<GoodsInfoRes> GoodsInfoList = new Page<GoodsInfoRes>(goodsInfoReques.getCurrent(), goodsInfoReques.getSize());
        List<GoodsInfoRes> GoodsInfoListPO = baseMapper.selectGoodsList(GoodsInfoList, wrapper);
        GoodsInfoList.setRecords(GoodsInfoListPO);
        //查询数据
        return GoodsInfoList;
    }


    /**
     * 同步商品信息
     */
    @Override
    public boolean syncGoodsInfo() {

        //开始更新
        boolean flg = redis.get(Constants.REDIS_MIYUAN_GOODS_INFO_SYNC, Boolean.class, Boolean.TRUE);
        if (!flg) {
            return false;
        }
        //使用多线程
        miyuanDataService.executor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    redis.set(Constants.REDIS_MIYUAN_GOODS_INFO_SYNC, Boolean.FALSE);
                    syncMiYuanGoodsInfo();
                    redis.set(Constants.REDIS_MIYUAN_GOODS_INFO_SYNC, Boolean.TRUE);
                } catch (Exception e) {
                    log.error("同步米源商品信息发生异常", e);
                    redis.set(Constants.REDIS_MIYUAN_GOODS_INFO_SYNC, Boolean.TRUE);
                }
            }
        });
        return true;
    }


    /**
     *
     */
    @Override
    public void syncMiyuanGoodsInfo() {
        syncMiYuanGoodsInfo();
    }


    /**
     * 同步米源数据
     */
    private void syncMiYuanGoodsInfo() {
        int n = 1;
        MiYuanModel<MiYuanPage<com.pactera.miyuangroup.vo.response.miyuan.GoodsInfo>> goodsinfos = miyuanDataService.getGoodsInfo(n, 200);
        while (true) {
            n++;
            //是否成功
            //失败，跳出，继续下一页
            if (!goodsinfos.isSuccess()) {
                continue;
            }

            //验证是否有数据，没有数据 跳出 继续下一页
            if (goodsinfos.getData() == null || goodsinfos.getData().getRecords() == null && goodsinfos.getData().getRecords().size() <= 0) {
                continue;
            }

            //更新商品集合
            List<GoodsInfo> upInfos = new ArrayList<>();
            //新增商品集合
            List<GoodsInfo> instInfos = new ArrayList<>();

            //循环数据入库
            for (com.pactera.miyuangroup.vo.response.miyuan.GoodsInfo goodsInfo : goodsinfos.getData().getRecords()) {
                //查询数据库是否存在数据
                EntityWrapper<GoodsInfo> ew = new EntityWrapper<>();
                if (StringUtils.isNotBlank(goodsInfo.getNumber())) {
                    ew.eq("number", goodsInfo.getNumber());
                } else {
                    ew.eq("original_id", goodsInfo.getId());
                }
                GoodsInfo info = selectOne(ew);
                if (null != info) {
                    //存在，更新数据
                    info.setClassification(goodsInfo.getClassification());
                    info.setName(goodsInfo.getName());
                    info.setNumber(goodsInfo.getNumber());
                    info.setOriginalId(goodsInfo.getId());
                    info.setPicture(goodsInfo.getPicture());
                    info.setPrice(goodsInfo.getPrice());
                    info.setSpecifications(goodsInfo.getSpecifications());
                    upInfos.add(info);
                } else {
                    //不存在，新增数据
                    info = new GoodsInfo();
                    info.setClassification(goodsInfo.getClassification());
                    info.setName(goodsInfo.getName());
                    info.setNumber(goodsInfo.getNumber());
                    info.setOriginalId(goodsInfo.getId());
                    info.setPicture(goodsInfo.getPicture());
                    info.setPrice(goodsInfo.getPrice());
                    info.setSpecifications(goodsInfo.getSpecifications());
                    instInfos.add(info);
                }
            }

            //更新
            if (upInfos.size() > 0) {
                updateBatchById(upInfos, upInfos.size());
            }
            //新增
            if (instInfos.size() > 0) {
                insertBatch(instInfos, instInfos.size());
            }

            //最后一页，退出
            if (goodsinfos.getData().isLast()) {
                break;
            }
            goodsinfos = miyuanDataService.getGoodsInfo(n, 100);
        }
    }
}
